//
//  QCComposePictureView.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/9.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

private let pictureViewCellId = "pictureViewCellId"
class QCComposePictureView: UICollectionView {

    //提供保存照片的数组
    var images:[UIImage] = [UIImage]()
    
    //定义一个闭包 无参数无返回值
    var closure:(()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        // 定义一个layout
        let flowLayout = UICollectionViewFlowLayout()
        
        //设置宽高
        let itemWH = (KSCREENW - 20 - 10)/3
        
        flowLayout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        //设置间距
        flowLayout.minimumLineSpacing = 5
        flowLayout.minimumInteritemSpacing = 5
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //给外界提供一个方法
    func addImage(image:UIImage){
        //添加image 显示配图
        isHidden = false
        //每次添加图片都是第一个
       images.insert(image, at: 0)
        //image数大于9 就移除最后面的
        if images.count > 9{
            images.removeLast()
        }
        //刷新UI
        reloadData()
    }
    //MARK: - 设置视图
    private func setupUI(){
        //默认隐藏配图
        isHidden = true
        backgroundColor = UIColor.white
        dataSource = self
        delegate = self
        register(QCComposePictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        
    }

}

extension QCComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
   //如果不添加 或者添加9张图片 那么就返回0 或者9张
    //如果在0-9之间时 需要多添加一张添加按图片
  
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = images.count
        
        if count == 0 || count == 9 {
            return count
        }else {
            return count + 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureViewCellId, for: indexPath) as! QCComposePictureViewCell
        if indexPath.item == images.count {
            cell.image = nil
        }else {
            //正常赋值
            cell.image = images[indexPath.item]
        }
        //实例化闭包
        cell.closure = {[weak self] in
            
            //删除images里面对应的元素
            self?.images.remove(at: indexPath.item)
            //如果images.count 为0那么隐藏button
            if self?.images.count == 0 {
                self?.isHidden = true
            }
            //刷新
            self?.reloadData()
        }
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        collectionView.deselectItem(at: indexPath, animated: true)
        //判断是最后一个加号按钮才执行闭包
        if indexPath.item == images.count {
            closure?()
        }
    }
    
}

class QCComposePictureViewCell: UICollectionViewCell {
    
    //定义一个闭包
    var closure:(()->())?
    
    //声明一个image属性 
    var image:UIImage? {
        didSet{
            //通过image值 来确定显示的图片
            if  image == nil {
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.isHidden = true
            }else {
                //正常
                bgImageView.image = image
                //高亮设置为nil 否则点击 显示加号图片
                bgImageView.highlightedImage = nil
                //显示正常图片 就显示删除按钮
                deleteButton.isHidden = false
            }
        }
    }
    
   override init(frame: CGRect) {
        super.init(frame: frame)
         setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        //约束
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        deleteButton.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
        }
        
    }
    //懒加载控件
    //显示的图片
    private lazy var bgImageView: UIImageView = UIImageView()
    //删除按钮
    private lazy var deleteButton: UIButton = {
       
        let button = UIButton()
        button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        button.setImage(UIImage(named:"compose_photo_close"), for: UIControlState.normal)
        return button
    }()
    
    @objc private func buttonClick(){
     
        //执行闭包
        closure?()
        
        
    }
}
